package cn.edu.thu.tsqualitylite.controller.fanDataProblem;

import javafx.util.Pair;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Map;

@Controller
public class StatisticsController
{
    static ArrayList<Pair<Integer, Integer>> ret = new ArrayList<Pair<Integer, Integer>>(){{add(new Pair<>(0,  0)); add(new Pair<>(0,  0)); add(new Pair<>(0,  0));}};
    @RequestMapping(value = "/api/fan-data-problem/statistics", method = RequestMethod.POST)
    @ResponseBody
    public ArrayList<Pair<Integer, Integer>> getStatistics(
            @RequestBody Map<String, Object> params
    ) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException
    {
        String operation = params.get("operation").toString();
        if(operation.equals("query"))
        {
            // System.out.println("query: " + ret);
            return ret;
        }
        else if(operation.equals("clear"))
        {
            for(int i = 0; i < ret.size(); i++)
                ret.set(i, new Pair<Integer, Integer>(0, 0));
            // System.out.println("clear: " + ret);
            return ret;
        }
        else if(operation.equals("update"))
        {
            // todo update element values
            Integer id = Integer.parseInt(params.get("id").toString());
            Integer key = Integer.parseInt(params.get("key").toString());
            Integer value = Integer.parseInt(params.get("value").toString());
            ret.set(id, new Pair<>(ret.get(id).getKey() + key, ret.get(id).getValue() + value));
            System.out.println("update: " + ret);
            return ret;
        }
        else
        {
            System.out.println("No such operation! " + ret);
            return ret;
        }
    }
}
